<template>
  <div id="LineWin">
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="线路标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入线路标题" />
        </el-form-item>
        <el-form-item label="线路专题" prop="topicId">
          <el-select
            v-model="form.topicId"
            placeholder="请选择线路专题"
            clearable
            size="small"
            style="width: 100%"
            @change="selecttopicId"

          >
            <el-option
              v-for="item in routeTopicList"
              :key="item.villageId"
              :label="`${item.topicName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="路线图片" prop="image">
          <ImageUpload
            v-model="form.image"
            @uploadImage="uploadImg"
            @remove="uploadImg"
            :limit="3"
          />
        </el-form-item>
        <el-form-item label="精选图片" prop="routeImage">
          <ImageUpload
            v-model="form.routeImage"
            @uploadImage="uploadrouteImage"
            @remove="uploadrouteImage"
            :limit='1'
          />
        </el-form-item>
        <el-form-item label="路线简介" prop="content">
          <!-- <editor v-model="form.content" :min-height="192" /> -->
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入路线简介"
            v-model="form.content"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="关联乡村" prop="villageIds">
          <el-select
            v-model="form.villageIds"
            placeholder="请选择关联乡村"
            multiple
            filterable
            clearable
            remote
            :remote-method="remoteVillageIdsMethod"
            size="small"
            style="width: 100%"
            @change="selectTownShipList"
          >
            <el-option
              v-for="item in townShipList"
              :key="item.villageId"
              :label="`${item.villageName}(${item.villageAddress})`"
              :value="item.villageId"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="地址类型" prop="">
          <el-radio-group v-model="addressType">
            <el-radio-button label="起始位置"></el-radio-button>
            <el-radio-button label="终点位置"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="起始位置" prop="startPosition" v-if="addressType === '起始位置'">
          <zxMap :value="latLng" :address="form.startPosition" v-if="open" @input="selectAddressClick"></zxMap>
        </el-form-item>
        <el-form-item label="终点位置" prop="endPosition" v-else>
          <zxMap :value="latLng" :address="form.endPosition" v-if="open" @input="selectAddressClick"></zxMap>
        </el-form-item> -->
        <el-form-item label="路线标签" prop="villageLabel">
          <el-select
            v-model="form.villageLabel"
            placeholder="请选择路线标签"
            clearable
            size="small"
          >
            <el-option
              v-for="(dict, i) in dict.type.village_label"
              :key="i"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="游玩天数(天)" prop="dayNumber">
          <el-input v-model="form.dayNumber" placeholder="请输入游玩天数" />
        </el-form-item>
        <el-form-item label="旅行开始时间" prop="startTime">
          <el-date-picker
            clearable
            size="small"
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择旅行开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="旅行结束时间" prop="endTime">
          <el-date-picker
            clearable
            size="small"
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择旅行结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否推荐" prop="isRecommend">
          <el-switch v-model="form.isRecommend" active-color="#13ce66" inactive-color="#ff4949" active-text="是"
            inactive-text="否">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTravelRoute,
  getTravelRoute,
  delTravelRoute,
  addTravelRoute,
  updateTravelRoute,
  exportTravelRoute,
  townShipList,
} from "@/api/route/travelRoute";
import ImageUpload from "@/components/UploadImage";
import zxMap from "@/components/map/index";
import Editor from "@/components/Editor";
import { townNameList } from "@/api/route/travelRoute";
import {
  listRouteTopic,
  getRouteTopic,
  delRouteTopic,
  addRouteTopic,
  updateRouteTopic,
  exportRouteTopic,
} from "@/api/route/routeTopic";

export default {
  name: "LineWin",
  dicts: ["travel_state", "village_label"],
  components: {
    ImageUpload,
    Editor,
    zxMap,
  },
  data() {
    return {
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [{ required: true, message: "请输入路线标题", trigger: "blur" }],
        content: [
          { required: true, message: "请输入路线简介", trigger: "blur" },
        ],
        villageLabel: [
          { required: true, message: "请选择路线标签", trigger: "change" },
        ],
        dayNumber: [
          { required: true, message: "请输入游玩天数（天）", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "请选择旅行开始时间", trigger: "change" },
        ],
        endTime: [
          { required: true, message: "请选择旅行结束时间", trigger: "change" },
        ],
        image: [{ required: true, message: "请上传路线图片", trigger: "blur" }],
        routeImage: [{ required: true, message: "请上传精选图片", trigger: "blur" }],
        startPosition: [
          {
            required: true,
            message: "请在地图上选择起始位置",
            trigger: "change",
          },
        ],
        endPosition: [
          {
            required: true,
            message: "请在地图上选择结束位置",
            trigger: "change",
          },
        ],
        villageIds: [
          { required: true, message: "请选择关联乡村", trigger: "blur" },
        ],
        topicId: [
          { required: true, message: "请选择线路专题", trigger: "blur" },
        ],
        endPosition: [
          {
            required: true,
            message: "请在地图上选择结束位置  ",
            trigger: "blur",
          },
        ],
      },
      //乡村标签
      villageGradeOptions: [],
      //起始位置经纬度
      latLng: undefined,
      // 乡村起始点
      townShipListStartId: undefined,
      townShipListEndId: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        topicName: null,
        topicImage: null,
      },
      // 路线专题
      routeTopicList:[],
      // 乡村列表
      townShipList:[],
    };
  },
  props: {
    title: {
      type: String,
      default: "",
    },
    lineId: {
      type: Number,
      default: 0,
    },
    timeStamp: {
      type: Number,
      default: 0,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    backFun: Function,
  },
  watch: {
    timeStamp: {
      handler(val) {
        this.reset();
        if (this.lineId) {
          this.getInfo();
          console.log(this.dict.type.travel_state)
          // console.log('this.townShipList',this.townShipList)
          // console.log('this.routeTopicList',this.routeTopicList);
        }
        // console.log('this.townShipList',this.townShipList)
        // console.log('this.routeTopicList',this.routeTopicList);
      },
      immediate: true,
    },
  },
  created() {
  },
  mounted(){ 
    console.log(this.dict.type.village_label)
   },
  methods: {
    selecttopicId(){
      console.log('selecttopicId',this.form.topicId);
    },
    // 输入框值发生改变
    async selectTownShipList(e) {
      // console.log("e", e);
      this.townShipListStartId = e.slice(0, 1);
      this.townShipListEndId = e.slice(-1);
      let startResult = await townNameList({
        villageId: this.townShipListStartId[0],
      });
      let endResult = await townNameList({
        villageId: this.townShipListEndId[0],
      });
      this.form.endPosition = endResult.rows[0].villageAddress;
      this.form.startPosition = startResult.rows[0].villageAddress;
    },
    // 弹窗初始化搜索500个展示(父组件传递)
    async showVillage() {
      let result = await townNameList({ pageSize: 500 });
      this.townShipList = result.rows;
      console.log(this.townShipList);
    },
    // 远程查询乡村数据列表
    async remoteVillageIdsMethod(query) {
      let result = await townNameList({ villageAddress: query });
      this.townShipList = result.rows;
        console.log("result", result);
    },
    // 点击修改
    getInfo() {
      getTravelRoute(this.lineId).then((response) => {
        // console.log("response", response);
        this.form = {
          ...this.form,
          ...response.data,
        };
        this.form.villageIds = [];
        response.data.routeVillages.forEach((item) => {
          this.form.villageIds.push(item.villageId);
        });
        this.townShipList = response.data.routeVillages;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let sendData = JSON.parse(JSON.stringify(this.form));
          // console.log("sendData", sendData);
          if (sendData.id != null) {
            updateTravelRoute(sendData).then((response) => {
              this.msgSuccess("修改成功");
              // sendData.id = response.data || sendData.id;
              this.cancel();
              if (this.backFun) {
                this.backFun(sendData);
              }
            });
          } else {
            addTravelRoute(sendData).then((response) => {
              this.msgSuccess("新增成功");
              this.cancel();
              if (this.backFun) {
                // sendData.agencyId = response.data || sendData.agencyId;
                this.backFun(sendData);
              }
            });
          }
        }
      });
    },
    //路线图片上传图片组件成功回调函数
    uploadImg(e) {
      this.form.image = e;
    },
      //路线图片上传图片组件成功回调函数
      uploadrouteImage(e) {
      this.form.routeImage = e;
    },
    //起始位置地图组件点击事件
    selectAddressClick(res) {
      if (this.addressType === "起始位置") {
        this.form.startPosition = res.address;
        this.form.startLongitude = res.lnglat.slice(0, res.lnglat.indexOf(","));
        this.form.startLatitude = res.lnglat.slice(
          res.lnglat.indexOf(",") + 1,
          res.lnglat.length
        );
      } else {
        this.form.endPosition = res.address;
        this.form.endLongitude = res.lnglat.slice(0, res.lnglat.indexOf(","));
        this.form.endLatitude = res.lnglat.slice(
          res.lnglat.indexOf(",") + 1,
          res.lnglat.length
        );
      }
    },
    reset() {
      this.form = {
        status: 1,
        agencyId: undefined,
      };
      this.resetForm("form");
    },
    cancel() {
      this.reset();
      this.visible = false;
    },
  },
};
</script>

<style scoped lang="scss">
#Agency {
}
</style>
